<template>
    <el-upload
      name="file"
      :show-file-list="false"
      accept=".png,.PNG,.jpg,.JPG,.jpeg,.JPEG,.gif,.GIF,.bmp,.BMP"
      :multiple="false"
      :http-request="uploadImage"
    >
      <div class="cover-upload-btn">
        <template v-if="localImageUrl">
          <img :src="localImageUrl" />
        </template>
        <span class="iconfont icon-add" v-else></span>
      </div>
    </el-upload>
  </template>
  
  <script>
  import { getCurrentInstance } from "vue";
  
  export default {
    name: "ImageUpload",
    props: {
      modelValue: {
        type: String,
        default: null,
      },
    },
    data() {
      return {
        api: {
          uploadUrl: "file/uploadImage",
        },
        localImageUrl: null,
      };
    },
    created() {
      this.proxy = getCurrentInstance().proxy;
    },
    methods: {
      uploadImage(file) {
        const fileReader = new FileReader();
        fileReader.onload = () => {
          const blob = new Blob([fileReader.result], { type: file.file.type });
          const blobUrl = URL.createObjectURL(blob);
          this.localImageUrl = blobUrl;

          // 将 Blob URL 发回父组件
          this.$emit("update:modelValue", blobUrl);
          this.$emit("callback", blobUrl);
          // this.localImageUrl = fileReader.result;
          // this.$emit("update:modelValue", file.file.name);
          // this.$emit("callback", file.file.name);
        };
        fileReader.readAsDataURL(file.file);
      },
    },
  };
  </script>
  
  <style lang="scss">
  .cover-upload-btn {
    background: url(../assets/cover_bg.png);
    width: 150px;
    height: 150px;
    display: flex;
    align-items: center;
    justify-content: center;
    .iconfont {
      font-size: 50px;
      color: rgb(164, 164, 164);
    }
    img {
      width: 100%;
    }
  }
  </style>